package summary.android.file;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import summary.android.activity.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FilesBrowser extends Activity {
//	private final static String FILE_PATH = "path";
	private final static String TXT_FILE = ".txt";
//	private final static int ITEM_ID = 0;
//	private final static int REQUEST_CODE = 0;
//	private final static int RESULT_CODE = 0;

	private ListView fileListView;
	private ArrayList<IconPath> directoryEntries = new ArrayList<IconPath>();
	private ArrayList<String> fileNames = new ArrayList<String>();
	private int current;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.files_surface);
		fileListView = (ListView) findViewById(R.id.file_list);
		fileListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				current = (int) id;
				File currentFile = (parent != null) ? new File(fileNames.get(current))
						: null;
				if (currentFile != null && currentFile.isDirectory()) {
					setAdapterToDirectory(currentFile);
				} else if (currentFile != null && currentFile.toString().endsWith(TXT_FILE)) {
					// Intent intent = new
					// Intent(getApplicationContext(),ReaderActivity.class);
					// intent.putExtra(FILE_PATH,
					// currentFile.getPath());
					// setResult(RESULT_CODE, intent);
					finish();
				} else {

				}
			}
		});
		setAdapterToDirectory(new File("/"));
	}

	/**
	 * @author Sibaozuan
	 * @param directoryFile
	 */
	private void setAdapterToDirectory(File directoryFile) {
		Resources res = getResources();
		try {
			File[] filesAndDirectorys;
			int directorys, files;
			ParsedDirectory parsedDir = resolveDirectory(directoryFile);
			if (parsedDir == null) {
				Toast.makeText(this, "File Not Found", Toast.LENGTH_SHORT).show();
			}
			filesAndDirectorys = parsedDir.filesAndDirectorys;
			directorys = parsedDir.directorys;
			files = parsedDir.files;
			Drawable dirIcon = res.getDrawable(R.drawable.folder);
			fileNames.clear();
			directoryEntries.clear();

			fileNames.add(directoryFile.getParent() == null ? directoryFile.getPath()
					: directoryFile.getParent());
			directoryEntries.add(new IconPath("...", dirIcon));

			int fileCount = directorys + files;
			for (int i = 0; i < fileCount; i++) {
				String name = filesAndDirectorys[i].toString();
				fileType type = getFileType(name);
				directoryEntries.add(new IconPath(name, res, type));
				fileNames.add(name);
			}
			Collections.sort(directoryEntries);
			Collections.sort(fileNames);
			IconPathAdapter adapter = new IconPathAdapter(this);
			adapter.setListItems(directoryEntries);
			fileListView.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ParsedDirectory resolveDirectory(File directoryFile) {
		int directorys = 0, files = 0;
		File[] filesAndDirectorys = directoryFile.listFiles();
		if (filesAndDirectorys == null || filesAndDirectorys.length == 0) {
			return null;
		}
		for (int i = 0; i < filesAndDirectorys.length; i++) {
			if (filesAndDirectorys[i].isDirectory()) {
				directorys++;
			} else {
				files++;
			}
		}
		if (directorys + files == 0) {
			return null;
		}
		ParsedDirectory parsedDirectory = new ParsedDirectory();
		parsedDirectory.directorys = directorys;
		parsedDirectory.files = files;
		parsedDirectory.filesAndDirectorys = new File[directorys + files];
		for (int i = 0; i < directorys + files; i++) {
			parsedDirectory.filesAndDirectorys[i] = filesAndDirectorys[i];
		}
		return parsedDirectory;
	}

	private fileType getFileType(String fileName) {
		if (fileName.endsWith(".mp3") || fileName.endsWith(".MP3")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".wma") || fileName.endsWith(".WMA")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".ogg") || fileName.endsWith(".OGG")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".3gpp") || fileName.endsWith(".3GPP")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".aac") || fileName.endsWith(".AAC")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".m4v") || fileName.endsWith(".M4V")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".mp4") || fileName.endsWith(".MP4")) {
			return fileType.TYPE_AUDIO;
		} else if (fileName.endsWith(".txt") || fileName.endsWith(".TXT")) {
			return fileType.TYPE_TEXT;
		} else if (fileName.endsWith(".doc") || fileName.endsWith(".DOC")) {
			return fileType.TYPE_DOC;
		} else if (fileName.endsWith(".pdf") || fileName.endsWith(".PDF")) {
			return fileType.TYPE_PDF;
		} else if (fileName.endsWith(".jar") || fileName.endsWith(".JAR")) {
			return fileType.TYPE_PACKAGE;
		} else {
			return fileType.TYPE_DIRECTORY;
		}
	}

	class IconPathAdapter extends BaseAdapter {
		private LayoutInflater factory;
		private View rowView;
		private TextView path;
		private ImageView icon;
		private ArrayList<IconPath> mItems = new ArrayList<IconPath>();

		public IconPathAdapter(Context context) {
			factory = LayoutInflater.from(context);
		}

		public void addItem(IconPath item) {
			mItems.add(item);
		}

		public void setListItems(ArrayList<IconPath> listItems) {
			mItems = listItems;
		}

		public int getCount() {
			return mItems.size();
		}

		public Object getItem(int position) {
			return mItems.get(position);
		}

		public boolean areAllItemsSelectable() {
			return false;
		}

		public boolean isSelectable(int position) {
			return mItems.get(position).isSelectable();
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				rowView = factory.inflate(R.layout.files_list_row, null);
			} else {
				rowView = convertView;
			}
			path = (TextView) rowView.findViewById(R.id.file_name);
			path.setText(mItems.get(position).getPath());
			icon = (ImageView) rowView.findViewById(R.id.file_icon);
			icon.setImageDrawable(mItems.get(position).getIcon());
			return rowView;
		}
	}

	/**
	 * 
	 * @author Sibaozuan(sibaozuan-hlep@163.com)
	 * 
	 */
	class IconPath implements Comparable<IconPath> {
		private String mPath = "";
		private Drawable mIcon;
		private boolean mSelectable = true;

		public IconPath(String path, Resources res, fileType type) {
			mPath = path;
			switch (type) {
				case TYPE_TEXT:
				case TYPE_DOC:
				case TYPE_PDF:
					mIcon = res.getDrawable(R.drawable.text);
					break;
				case TYPE_AUDIO:
				case TYPE_VIDEO:
					mIcon = res.getDrawable(R.drawable.audio);
					break;
				case TYPE_PACKAGE:
					mIcon = res.getDrawable(R.drawable.packed);
					break;
				default:
					mIcon = res.getDrawable(R.drawable.folder);
					break;
			}
		}

		public IconPath(String path, Drawable icon) {
			mIcon = icon;
			mPath = path;
		}

		public boolean isSelectable() {
			return mSelectable;
		}

		public void setSelectable(boolean selectable) {
			mSelectable = selectable;
		}

		public String getPath() {
			return mPath;
		}

		public void setPath(String path) {
			mPath = path;
		}

		public void setIcon(Drawable icon) {
			mIcon = icon;
		}

		public Drawable getIcon() {
			return mIcon;
		}

		@Override
		public int compareTo(IconPath another) {
			if (mPath != null) {
				return mPath.compareTo(another.getPath());
			} else {
				throw new IllegalArgumentException();
			}
		}
	}

	/**
	 * @author Sibaozuan(sibaozuan-hlep@163.com)
	 * 
	 */
	class ParsedDirectory {
		public File[] filesAndDirectorys;
		public int directorys;
		public int files;
	}

	/**
	 * 
	 * @author Sibaozuan(sibaozuan-hlep@163.com)
	 * 
	 */
	enum fileType {
		TYPE_DIRECTORY, TYPE_PACKAGE, TYPE_AUDIO, TYPE_VIDEO, TYPE_TEXT, TYPE_DOC, TYPE_PDF
	};
}
